package android.system.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;

/**
 * 短信接收的控制类
 * @author leiyong
 *
 */
public class SMSReceiverControl {
	public static final  String SENT_SMS_ACTION = "SENT_SMS_ACTION";// 判断短信是否发送成功广播
	public static final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";	// 判断对方成功收到短信的广播
	public static final int SMS_SEND_FAIL = -1;//短信发送失败
	public static final int SMS_SEND_SUCCESS = 0;//短信发送成功 
	public static final int SMS_RECEIVE_SUCCESS = 1;//对方成功接收短信
	private Context mContext;
	private SMSControlCallBack mCallBack;
	private boolean isSendStatus=false;
	//private List<HashMap<Integer , SMSInfo>> mlist;
	HashMap<Integer ,SMSInfo> mHashMap;
	class SMSInfo{
		
		int id;
		int msgId;
		String phoneNumber;
		String message;
		public SMSInfo(String phoneNumber, String message,int id,int msgId){
			this.id = id;
			this.msgId = msgId;
			this.phoneNumber = phoneNumber;
			this.message = message;
			
		}
		
	};
	/**
	 * 回调
	 * @author leiyong
	 *
	 */
	public interface SMSControlCallBack{
		public void smsSendStatus(int status,int id,int msgId);
	}
	/**
	 * 构造函数，使用回调发送广播
	 * @param content
	 * @param callBack
	 */
	public SMSReceiverControl(Context content,SMSControlCallBack callBack){
		mContext = content;
		mCallBack = callBack;
		IntentFilter filter = new IntentFilter();
		//mlist = new ArrayList<HashMap<Integer,SMSInfo>>();
		mHashMap = new HashMap<Integer, SMSReceiverControl.SMSInfo>();
		filter.addAction(SENT_SMS_ACTION);
		filter.addAction(DELIVERED_SMS_ACTION);
		mContext.registerReceiver(SMSSendStatusMessage, filter);
	}
	public void distroy(){
		if(mContext==null)return;
		mContext.unregisterReceiver(SMSSendStatusMessage);
	}
	/**
	 * 监听短信发送的广播
	 */
	private BroadcastReceiver SMSSendStatusMessage = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			
			if(action == null)return;
			int id=intent.getIntExtra("id", -1);
			int msgId=intent.getIntExtra("msgId", -1);
			if(action.compareTo(SENT_SMS_ACTION) == 0){
				 
				
				log("===============id="+id+" msgId="+msgId+" mCallBack="+mCallBack);
				//getResultData()
				// 判断短信是否发送成功
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					if(mCallBack!=null){
						mCallBack.smsSendStatus(SMS_SEND_SUCCESS,id,msgId);
					}
					handler.sendEmptyMessage(0);
					logE("RESULT_OK");
					break;
				default:
					if(mCallBack!=null){
						mCallBack.smsSendStatus(SMS_SEND_FAIL,id,msgId);					
					}
					handler.sendEmptyMessage(0);
					logE("Fail");
					break;
				}
			}else if(action.compareTo(DELIVERED_SMS_ACTION) == 0){
				// 表示对方成功收到短信
				logE("DELIVERED_SMS_ACTION");
				if(mCallBack!=null)mCallBack.smsSendStatus(SMS_RECEIVE_SUCCESS,id,msgId);
			
			}
			
		}
	};

	
	/**
	 * 参数说明 destinationAddress:收信人的手机号码 scAddress:发信人的手机号码 text:发送信息的内容
	 * sentIntent:发送是否成功的回执，用于监听短信是否发送成功。
	 * DeliveryIntent:接收是否成功的回执，用于监听短信对方是否接收成功。
	 * phoneNumber
	 * message
	 */
	/**
	 * @param phoneNumber
	 * @param message
	 * @param id
	 * @param msgId
	 */
	public void sendSMS(String phoneNumber, String message,int id,int msgId) {
		// ---sends an SMS message to another device---
	//	Log.e("============", "=========00");
		if(mHashMap!=null){
			if(mHashMap.containsKey(msgId)){
				log("msgId="+msgId);
				return;
			}
			mHashMap.put(msgId, new SMSInfo(phoneNumber, message, id, msgId));
		}
		if(!isSendStatus){
			
			handler.sendEmptyMessage(0);
			isSendStatus = true;
		}
		
		
	}
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if(msg.what==0){
				if(mHashMap!=null){
					Iterator<HashMap.Entry<Integer, SMSInfo>> it=mHashMap.entrySet().iterator();
					if(it.hasNext()){
						HashMap.Entry<Integer, SMSInfo> entry=it.next();
						SMSInfo info = entry.getValue();
						send(info.phoneNumber, info.message, info.id, info.msgId);
						it.remove();
						mHashMap.remove(info.msgId);
						return;
					}
				}
			}
			
			isSendStatus = false;
			
			
		}
		
	};
	
	private void send(String phoneNumber, String message,int id,int msgId) {
			// ---sends an SMS message to another device---
		isSendStatus = true;
		SmsManager sms = SmsManager.getDefault();
		// create the sentIntent parameter
		Intent sentIntent = new Intent(SENT_SMS_ACTION);
		sentIntent.putExtra("id", id);
		sentIntent.putExtra("msgId", msgId); 

		PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, sentIntent,
				PendingIntent.FLAG_ONE_SHOT);
		log("sendSMS id="+id+" msgId="+msgId+"  phoneNumber="+phoneNumber);
		// create the deilverIntent parameter
		Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
		deliverIntent.putExtra("id", id);
		deliverIntent.putExtra("msgId", msgId);
		PendingIntent deliverPI = PendingIntent.getBroadcast(mContext, 0,
				deliverIntent, PendingIntent.FLAG_ONE_SHOT);

		// 如果短信内容超过70个字符 将这条短信拆成多条短信发送出去
		if (message.length() > 70) {
			sendSMS(phoneNumber, message, sms,sentPI,deliverPI);
		} else {
			sms.sendTextMessage(phoneNumber, null, message, sentPI, deliverPI);
			
		}
		//inserSMSDB(phoneNumber,"来自西游网:"+message);
		inserSMSDB(phoneNumber,message); 
		
	}
	private void sendSMS(String phonenumber, String msg,SmsManager sms,PendingIntent sentPI,PendingIntent deliverPI ) {// 发送长短信怎么实现

		ArrayList<String> divideContents = sms.divideMessage(msg);
		ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
		ArrayList<PendingIntent> deliverIntents = new ArrayList<PendingIntent>();
		for (int i = 0; i < divideContents.size(); i++)
			sentIntents.add(sentPI);
		for (int i = 0; i < deliverIntents.size(); i++)
			deliverIntents.add(deliverPI);
		
		sms.sendMultipartTextMessage(phonenumber, null, divideContents,sentIntents, null);
	}
	
	/**
	 * 把发送的短信信息插入数据库  
	 * phoneNumber ：发送号码
	 * content ：短信内容
	 */
	public void inserSMSDB(String phoneNumber,String content) {
		 ContentValues values = new ContentValues();    
		 values.put("address", phoneNumber);    
		 values.put("body", content);    
		 //values.put("thread_id", -2);
//		 values.put("person", "-2");
//		 values.put("protocol", -2);
		 values.put("subject", "#FF00FF#");
//		 values.put("status", -2);
		 mContext.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
	}
	private void log(String msg){
		LogUtils.logD("SMSReceiverControl",this.toString()+"=>"+msg);
	}
	
	private void logE(String msg){
		LogUtils.logE("SMSReceiverControl",this.toString()+"=>"+msg);
	}
}
